package com.zlq.cn.service.tian;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zlq.cn.entity.TianStarinfo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import one.util.streamex.StreamEx;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhoucl
 * @date 2023年05月08日 10:32
 */
@Slf4j
@Component
public class TianService {

    @Resource
    private TianStarinfoService tianStarinfoService;

    @Resource
    private TianConfigService.TianApiService tianApiService;

    @SneakyThrows
    public List<TianStarinfo> starinfo(TianStarinfo param) {
        List<TianStarinfo> list = tianStarinfoService.lambdaQuery().eq(TianStarinfo::getName, param.getName()).list();
        if (CollectionUtil.isEmpty(list)) {
            list = tianApiService.starinfo(param.getName(), param.getSex(), param.getNationality(), param.getBirthDate(),
                    param.getConstellation(), param.getPage(), param.getNum()).execute().body().checkCode().getList();
            if (CollectionUtil.isNotEmpty(list)) {
                for (TianStarinfo tianStarinfo : list) {
                    tianStarinfo.setCreateTime(LocalDateTime.now());
                }
                // 明星名字可能相同，用头像来做唯一区分
                Set<String> extSet = tianStarinfoService.lambdaQuery()
                        .in(TianStarinfo::getImageURL, StreamEx.of(list).map(TianStarinfo::getImageURL).toList())
                        .list().stream().map(TianStarinfo::getImageURL).collect(Collectors.toSet());
                StreamEx.of(list).filter(it -> !extSet.contains(it.getImageURL())).toListAndThen(tianStarinfoService::saveBatch);
            }
        }
        return list;
    }

    public Page<TianStarinfo> starinfoList(Page<TianStarinfo> page, TianStarinfo param) {
        return tianStarinfoService.lambdaQuery()
                .like(StringUtils.isNotEmpty(param.getName()), TianStarinfo::getName, param.getName())
                .page(page);
    }
}
